package com.andy.base.conn;

import com.andy.base.config.ServerConfig;
import com.andy.base.mapper.Engine;
import com.sun.org.apache.bcel.internal.generic.NEW;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class Connector {

    private Engine engine;
    private ServerConfig serverConfig;
    private ThreadPoolExecutor threadPoolExecutor;

    public Connector(Engine engine, ServerConfig serverConfig) {
        this.engine = engine;
        this.serverConfig = serverConfig;
        initExecutor();
    }

    /**
     * 初始化线程池
     */
    private void initExecutor(){
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
    }

    public void start() throws Exception{
        //接收TCP连接
        int port = Integer.parseInt(serverConfig.getPort());
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("mini cat 启动完成");
        //分发接到的连接给线程池处理
        while(true){
            Socket socket = serverSocket.accept();
            threadPoolExecutor.execute(new RequestProcessor(engine,serverConfig,socket));
        }

    }
}
